<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getReports } from "@/api/report";

import { uploadByServer } from "@/api/report";
defineOptions({
  name: "Result"
});

const list = ref([]);

const loadData = async () => {
  const res = await getReports();
  console.log(res);
  list.value = res.data.map(it => it.replace(".json", ""));
};

onMounted(() => {
  loadData();
});

const httpRequest = data => {
  console.log("自定义上传", data);
  // 封装FormData对象
  const formData = new FormData();
  formData.append("file", data.file);
  console.log("formData", formData);
  // 调用后端接口
  uploadByServer(formData)
    .then(() => {
      alert("上传成功！");
      loadData();
    })
    .catch(err => {
      console.log(err);
    });
};

const beforeAvatarUpload = file => {
  const isType = file.type === "application/json";

  if (!isType) {
    alert("上传必须是json格式");
  }
  return isType;
};
</script>

<template>
  <div class="main">
    <div class="w-full flex justify-between mb-4">
      <el-upload
        action="#"
        ref="upload"
        :show-file-list="false"
        :http-request="httpRequest"
        :before-upload="beforeAvatarUpload"
      >
        <el-button size="small" type="primary"> 上传新报告 </el-button>
        <template #tip>
          <div class="el-upload__tip">
            json格式,文件名示例： 2023.12.13-学习通道测评表-分数
          </div>
        </template>
      </el-upload>
    </div>
    <div>
      <el-empty v-show="list.length === 0" description="暂无数据" />

      <div v-if="list.length">
        <h4 style="margin: 1em 0">已有报告</h4>
        <ul>
          <li v-for="(file, index) in list" :key="index">
            {{ index + 1 }}.
            <router-link class="link" :to="`/result/detail/${file}`">{{
              file
            }}</router-link>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped>
.link {
  color: var(--el-color-primary);
}
</style>
